package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.InteractionReviewBean;
import com.atguigu.util.ClickHouseUtil;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsInteractionReviewWindow {
    public static void main(String[] args) throws Exception {

        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        // TODO 2 设置状态后端
         /*
         env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
         env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
         env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
         env.setStateBackend(new HashMapStateBackend());
         env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
         System.setProperty("HADOOP_USER_NAME", "atguigu");
         */

        //todo 3 读取dwd层数据
        String topicName = "dwd_interaction_review";
        String groupId = "dws_interaction_review_window";
        DataStreamSource<String> reviewStream = env.addSource(KafkaUtil.getFlinkKafkaConsumer(topicName, groupId));

        //todo 4 转换结构
        SingleOutputStreamOperator<JSONObject> mapStream = reviewStream.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSON.parseObject(value);
            }
        });


        //todo 5 根据course_id去重和转换为javabean
        SingleOutputStreamOperator<InteractionReviewBean> beanStream = mapStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("user_id");
            }
        }).flatMap(new RichFlatMapFunction<JSONObject, InteractionReviewBean>() {

            ValueState<String> lastVisitorState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> lastVisitDtDescroptor = new ValueStateDescriptor<>("last_visit_dt", String.class);
                lastVisitDtDescroptor.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1l))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());
                lastVisitorState = getRuntimeContext().getState(lastVisitDtDescroptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<InteractionReviewBean> out) throws Exception {
                String lastDt = lastVisitorState.value();
                long visitDt = value.getLong("ts") * 1000l;
                String date = DateFormatUtil.toDate(visitDt);

                long uc = 0L;
                if (lastDt == null || (lastDt != null && !lastDt.equals(date))) {
                    uc = 1;
                    lastVisitorState.update(date);
                } else {
                    uc = 0;
                }

                out.collect(new InteractionReviewBean("", "", value.getString("user_id"), uc, value.getString("course_id")
                        ,value.getLong("review_stars"), Long.parseLong(value.getString("ts"))));
            }
        });


        //todo 5开窗聚合
        SingleOutputStreamOperator<InteractionReviewBean> reduceStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<InteractionReviewBean>forBoundedOutOfOrderness(Duration.ofSeconds(2l))
                .withTimestampAssigner(new SerializableTimestampAssigner<InteractionReviewBean>() {

                    @Override
                    public long extractTimestamp(InteractionReviewBean element, long recordTimestamp) {
                        return element.getTs()*1000L;
                    }
                }))
                .keyBy(new KeySelector<InteractionReviewBean, String>() {
                    @Override
                    public String getKey(InteractionReviewBean value) throws Exception {
                        return value.getCourse_id();
                    }
                })
                .window(TumblingEventTimeWindows.of(Time.seconds(10l)))
                .reduce(new ReduceFunction<InteractionReviewBean>() {
                    @Override
                    public InteractionReviewBean reduce(InteractionReviewBean value1, InteractionReviewBean value2) throws Exception {
                        value1.setUc(value1.getUc()+value2.getUc());
                        value1.setReview_stars(value1.getReview_stars() + value2.getReview_stars());
                        return value1;
                    }
                }, new WindowFunction<InteractionReviewBean, InteractionReviewBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<InteractionReviewBean> input, Collector<InteractionReviewBean> out) throws Exception {
                        InteractionReviewBean next = input.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setTs(System.currentTimeMillis());
                        out.collect(next);
                    }
                });

        reduceStream.addSink(ClickHouseUtil.getClickHouseSink("insert into dws_interaction_review_window values (?,?,?,?,?,?,?)"));

        //执行
        env.execute();
    }
}
